package org.hive.vmware.persistence;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Access to Projects, Test Runs, and dependent objects persisted to disk.
 * Disk structure:
 * {user dir}/ .vmwarehive / vmwarecenterserver.txt 
 * {user dir}/ .vmwarehive / vmgroups.txt 
 */
public class DiskPersistence {

	public static final String ROOT_DIRECTORY_NAME = ".vmwarehive";
	public static final String FILE_SEPARATOR = System.getProperty("file.separator");
	public static final String USER_DIRECTORY = System.getProperty("user.home");
	public static final String VMCENTERS_FIlE = "vmwarecenterservers.txt";
	public static final String VMGROUP_FIlE = "vmgroups.txt";	

	private static final String FILE_PATH = USER_DIRECTORY 
													+ FILE_SEPARATOR 
													+ ROOT_DIRECTORY_NAME
													+ FILE_SEPARATOR; 

	private static final String VMCENTER_FILE_PATH = FILE_PATH + VMCENTERS_FIlE;
	private static final String VMGROUP_FIlE_PATH = FILE_PATH + VMGROUP_FIlE;
	
	public DiskPersistence() {
		forceMakeDir();
	}
	
	private void forceMakeDir() {
		File file = new File(USER_DIRECTORY + FILE_SEPARATOR + ROOT_DIRECTORY_NAME);
		if (!file.exists()) {
			file.mkdir();
		}
	}
	
	public void saveVmwareCenterServers(List<String> vmcenters) throws IOException{
		File file = new File(VMCENTER_FILE_PATH);
		saveData(file, vmcenters);
	}

	public List<String> loadVmwareCenterServers() throws IOException{
		File file = new File(VMCENTER_FILE_PATH);
		return loadData(file);
	}
	
	public void saveVmGroups(List<String> vmGroups) throws IOException {
		File file  = new File(VMGROUP_FIlE_PATH);
		saveData(file, vmGroups);
	}
	
	public List<String> loadVmGroups() throws IOException{
		File file = new File(VMGROUP_FIlE_PATH);
		return loadData(file);
	}
	
	List<String> loadData(File file) throws IOException {
		List<String> data = new ArrayList<String>();
		BufferedReader bufferedReader = null;
		
		try {
			
			if (!file.exists()) {
				file.createNewFile();
			}
			bufferedReader = new BufferedReader(new FileReader(file));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				data.add(line);
			}
			
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
		}
		return data;
	}
	
	void saveData(File file, List<String> data) throws IOException {
		BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
		try {
			if (!file.exists()) {
				file.createNewFile();
			}
			for (String line : data) {
				bufferedWriter.write(line);
				System.out.println("writing to " + file.getName() + ":" + line);
				bufferedWriter.newLine();
			}
		} finally {
			bufferedWriter.flush();
			bufferedWriter.close();
		}
	}
}
